/*
   Copyright 2008 Alex Radeski

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package org.ezaero.bushel;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.DirSet;
import org.apache.tools.ant.types.Resource;
import org.apache.tools.ant.types.resources.FileResource;

public class BushelAntTask extends Task {

    private File destDir;

    private File srcDir;
    
    private boolean verbose;

    private final List<DirSet> dirSets = new ArrayList<DirSet>();

    public void setDestdir(File dir) {
        this.destDir = dir;
    }

    public void setSrcdir(File dir) {
        this.srcDir = dir;
    }
    
    public void setVerbose(boolean verbose) {
        this.verbose = verbose;
    }

    public void addDirset(DirSet dirSet) {
        dirSets.add(dirSet);
    }

    @SuppressWarnings("unchecked")
    public void execute() throws BuildException {
        destDir.mkdirs();
        
        checkDir(destDir, "Invalid destination dir:" + destDir);

        if (srcDir != null && !dirSets.isEmpty()) {
            throw new BuildException("User either 'srcdir' or nested 'dirset', not both");
        }

        final List<File> srcDirs = new ArrayList<File>();

        if (srcDir != null) {
            checkDir(srcDir, "Invalid source dir:" + srcDir);
            srcDirs.add(srcDir);
        } else {
            for (DirSet dirSet : dirSets) {
                for (Iterator<Resource> it = dirSet.iterator(); it.hasNext();) {
                    final File dir = ((FileResource) it.next()).getFile();
                    checkDir(dir, "Invalid source dir in dirset:" + dir);
                    srcDirs.add(dir);
                }

            }
        }

        new Bushel(destDir, srcDirs, verbose).run();
    }

    private void checkDir(File dir, String msg) {
        if (!dir.canWrite() || !dir.isDirectory()) {
            throw new BuildException(msg);
        }
    }
}
